package com.mukefile.utils;


import com.alibaba.fastjson.JSON;
import com.mukefile.dto.KnsFile;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author xinke.huang@hand-china.com
 * @version 1.0
 * @date 2021/2/4
 */
public class CommonUtil {
    public static final Long KB = 1024L;
    public static final Long MB = 1024*1024L;
    public static final Long GB = 1024*1024*1024L;
    /**
     * 响应json格式字符串
     * @param object
     * @throws IOException
     */
    public static void responseJSON(Object object) throws IOException {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setCharacterEncoding("utf-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.write(JSON.toJSONString(object));
        printWriter.flush();
        printWriter.close();
    }


    /**
     * 将字节数转换为文件可视化大小
     * @param fileByte
     * @return 1024 -> 1KB
     */
    public static String byte2Size(Long fileByte){
        String size = "0B";
        if (Objects.isNull(fileByte)){
            return "---";
        }
        if (fileByte<KB){
            size = fileByte+"B";
        } else if (fileByte < MB){
            size = String.format("%.2f",(double)fileByte/KB)+"KB";
        } else if (fileByte < GB){
            size = String.format("%.2f",(double)fileByte/MB)+"MB";
        } else {
            size = String.format("%.2f",(double)fileByte/GB)+"GB";
        }
        return size;
    }

    /**
     * 日期格式转换
     * @param timestamp
     * @return
     */
    public static String timestamp2Format(Timestamp timestamp){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return timestamp.toLocalDateTime().format(formatter);
    }

    /**
     * 获取文件扩展名
     * @param filename 文件名
     * @return
     */
    public static String getFileExtension(String filename){
        if (filename.contains(".")){
            return filename.substring(filename.lastIndexOf("."));
        } else {
            return "";
        }
    }
}
